package reference;

import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;

/**
 * @program JavaBase
 * @description: 软引用，适合做缓存
 *  jvm堆内存不够用且垃圾回收仍然不够，会删除软引用
 * @author: zhanglu
 * @create: 2020-12-13 17:00:00
 */
public class Re02_SoftRefernce {

    public static void main(String[] args) throws Exception {
        SoftReference<byte[]> softReference = new SoftReference<>(new byte[1024 * 1024 * 10]);
        System.out.println(softReference.get());
        System.out.println(Runtime.getRuntime().totalMemory() / (1024*1024));
        System.out.println(Runtime.getRuntime().freeMemory() / (1024*1024));
        System.gc();
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println(softReference.get());
        System.out.println(Runtime.getRuntime().totalMemory() / (1024*1024));
        System.out.println(Runtime.getRuntime().freeMemory() / (1024*1024));
        byte[] bytes = new byte[1024 * 1024 * 5];
        System.out.println(softReference.get());
        System.out.println(Runtime.getRuntime().totalMemory() / (1024*1024));
        System.out.println(Runtime.getRuntime().freeMemory() / (1024*1024));
        bytes = null;
        System.gc();
        TimeUnit.MILLISECONDS.sleep(500);
        System.out.println(Runtime.getRuntime().totalMemory() / (1024*1024));
        System.out.println(Runtime.getRuntime().freeMemory() / (1024*1024));
        byte[] bytes2 = new byte[1024 * 1024 * 10];
        System.out.println(softReference.get());
        System.out.println(Runtime.getRuntime().totalMemory() / (1024*1024));
        System.out.println(Runtime.getRuntime().freeMemory() / (1024*1024));
    }



}
